<template>
  <div class="app-container flex-cloumn">
    <el-form :model="queryParams" ref="queryRef">
      <el-row :gutter="12">
        <el-col :span="4">
          <el-form-item label="部门名称" prop="deptName">
            <el-input
                v-model="queryParams.deptName"
                placeholder="请输入部门名称"
                clearable
                :style="{width: '100%'}"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" :style="{width: '100%'}" placeholder="部门状态" clearable>
              <el-option
                  v-for="dict in sys_normal_disable"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" icon="Search" style="margin: 3px 3px"
                       v-hasPermi="['system:dept:list']" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" style="margin: 3px 3px"
                       v-hasPermi="['system:dept:reset']" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="12">

        <el-button
            type="primary"
            style="margin: 3px 3px"
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:dept:add']"
        >新增
        </el-button>

        <el-button
            type="warning"
            style="margin: 3px 3px"
            icon="Edit"
            :disabled="rowSelect"
            @click="handleBeforeUpdate()"
            v-hasPermi="['system:dept:edit']"
        >修改
        </el-button>

        <el-button
            type="danger"
            style="margin: 3px 3px"
            :disabled="delDisable"
            icon="Delete"
            @click="handleBeforeDelete()"
            v-hasPermi="['system:dept:remove']"
        >删除
        </el-button>

        <el-button
            type="info"
            style="margin: 3px 3px"
            icon="Sort"
            @click="toggleExpandAll"
        >展开/折叠
        </el-button>

        <el-button
            type="primary"
            style="margin: 3px 3px"
            icon="User"
            @click="handleAllocateUser"
            :disabled="rowSelect"
            v-hasPermi="['system:dept:allocate']"
        >分配用户
        </el-button>


    </el-row>

    <xTable
        ref="deptTable"
        refId="deptTable"
        v-if="refreshTable"
        v-loading="loading"
        :data="deptList"
        row-key="deptId"
        multiple="false"
        @selection-change="handleSelectionChange"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <template #columList>
        <el-table-column prop="deptName" label="部门名称"></el-table-column>
        <el-table-column prop="deptCode" label="部门编码" width="150"></el-table-column>
        <el-table-column prop="orderNum" label="排序" width="200"></el-table-column>
        <el-table-column prop="status" label="状态" width="200">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column prop="leader" label="负责人" width="200" :formatter="leaderFormatter"
                         :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="false" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
                type="text"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:dept:edit']"
            >修改
            </el-button>
            <el-button
                type="text"
                icon="Plus"
                @click="handleAdd(scope.row)"
                v-hasPermi="['system:dept:add']"
            >新增
            </el-button>
            <el-button
                v-if="scope.row.parentId != 0"
                type="text"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:dept:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </template>
    </xTable>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :close-on-click-modal="false"  destroy-on-close  draggable="true" :title="title" v-model="open" width="600px"
               append-to-body>
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
        <el-row>

          <el-col :span="12">
            <el-form-item label="部门编码" prop="deptCode">
              <el-input v-model="form.deptCode" :disabled="deptCodeDisabled" placeholder="请输入部门编码" maxlength="20"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" maxlength="30" placeholder="请输入部门名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <el-tree-select
                  style="width:100%"
                  v-model="form.parentId"
                  :data="deptOptions"
                  :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                  value-key="deptId"
                  placeholder="选择上级部门"
                  check-strictly
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" style="width:100%" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>


          <el-col :span="12" v-show="false">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="false">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in sys_normal_disable"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--分配用户对话框-->
    <el-dialog :title="allocateTitle" v-model="allocateOpen" draggable="true"
               :close-on-click-modal="false" width="800px" :height="dialogHeight" append-to-body>

      <el-form :model="allocateQueryParams" ref="allocateQueryRef" :inline="true">

        <!-- <el-form-item label="部门名称" >
           <tree-select
                    v-model="allocateQueryParams.deptId"
                    :options="deptOptions"
                    style="width:100%"
                    placeholder="请选择归属部门"
                    :objMap="{ value: 'deptId', label: 'deptName', children: 'children' }"
                 />
        </el-form-item> -->

        <el-form-item label="用户编号" prop="userName">
          <el-input
              v-model="allocateQueryParams.userName"
              placeholder="请输入用户编号"
              clearable
              @keyup.enter="handleAllocateQuery"
          />
        </el-form-item>

        <el-form-item label="用户名称" prop="nickName">
          <el-input
              v-model="allocateQueryParams.nickName"
              placeholder="请输入用户名称"
              clearable
              @keyup.enter="handleAllocateQuery"
          />
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8" style="margin-top:5px">
        <el-col :span="1.5">
          <el-button type="primary" icon="Search" @click="handleAllocateQuery">
            搜索
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="text" icon="User"
                     :disabled="allocateMultiple || adminShow" @click="submitAllocate">
            分配
          </el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button type="danger" icon="CircleClose"
                     :disabled="allocateMultiple || adminShow" @click="submitDisAllocate">
            取消分配
          </el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button @click="allocateOpen = false">
            取 消
          </el-button>
        </el-col>
      </el-row>


      <el-row>
        <xTable ref="allocateUserTable" refId="allocateUserTable"
                v-loading="allocateLoading" :data="allocateUserList" :style="{height:screenHeight , overflow:'auto'}"
                @selection-change="allocateUserHandleSelectionChange">

          <template #columList>
            <el-table-column label="用户编号" align="center" prop="userName" :show-overflow-tooltip="true"/>
            <el-table-column label="用户名称" align="center" prop="nickName" :show-overflow-tooltip="true"/>
            <el-table-column label="员工编号" align="center" prop="uuid" :show-overflow-tooltip="true"/>
            <el-table-column label="所属部门" align="center" prop="deptName" :show-overflow-tooltip="true"/>
            <el-table-column label="是否分配" align="center" prop="ifAllocate">
              <template #default="scope">
                <dict-tag :options="allocatFlag" :value="scope.row.status"/>
              </template>
            </el-table-column>

          </template>
        </xTable>

        <pagination
            v-show="allocateUserTotal > 0"
            :total="allocateUserTotal"
            v-model:page="allocateQueryParams.pageNum"
            v-model:limit="allocateQueryParams.pageSize"
            @pagination="getAllocateUser"
        />
      </el-row>
    </el-dialog>

  </div>
</template>

<script setup name="Dept">
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
  listAllocateUser,
  allocateUsers,
  disAllocateUsers
} from "@/api/system/dept";
import {isNotVoid, isVoid} from "../../../utils/util";
import store from '@/store'
import useUserStore from "../../../store/modules/user";
const {proxy} = getCurrentInstance();
const {sys_normal_disable} = proxy.useDict("sys_normal_disable");

const {allocatFlag} = proxy.useDict("allocatFlag");


const deptList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const deptOptions = ref([]);
const isExpandAll = ref(true);
const refreshTable = ref(true);

const deptCodeDisabled = ref(false);

const deptId = ref();
const allocateUserList = ref([]);
const allocateTitle = ref("");
const allocateOpen = ref(false);
const rowSelect = ref(true);
const selectRowData = ref([]);
const allocateLoading = ref(true);
const allocateUserTotal = ref(0);
const delDisable = ref(false);
const adminShow = ref(false);

const userIds = ref([]);
const allocateSingle = ref(true);
const allocateMultiple = ref(true);

const screenHeight = ref(document.documentElement.clientHeight - 350 + "px");
const dialogHeight = ref(document.documentElement.clientHeight - 200 + "px");

const data = reactive({
  form: {},
  queryParams: {
    deptName: undefined,
    status: undefined
  },
  allocateQueryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: undefined,
    deptName: undefined,
    userName: undefined,
    nickName: undefined
  },
  rules: {
    deptCode: [{required: true, message: "部门编码不能为空", trigger: "change"}],
    parentId: [{required: true, message: "上级部门不能为空", trigger: "change"}],
    deptName: [{required: true, message: "部门名称不能为空", trigger: "change"}],
    orderNum: [{required: true, message: "显示排序不能为空", trigger: "change"}],
    email: [{type: "email", message: "'请输入正确的邮箱地址", trigger: ["blur", "change"]}],
    phone: [{pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}]
  },
});

const {queryParams, form, rules, allocateQueryParams} = toRefs(data);

/** 查询部门列表 */
function getList() {
  loading.value = true;
  listDept(queryParams.value).then(response => {
    deptList.value = proxy.handleTree(response.data, "deptId");
    loading.value = false;
  });
}

function getAllocateUser() {
  allocateLoading.value = true;
  listAllocateUser(allocateQueryParams.value).then(response => {
    allocateUserList.value = response.rows;
    allocateUserTotal.value = response.total;
    allocateLoading.value = false;
  });
}


/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    deptId: undefined,
    deptCode: undefined,
    parentId: undefined,
    deptName: undefined,
    orderNum: 0,
    leader: undefined,
    phone: undefined,
    email: undefined,
    status: "0"
  };
  proxy.resetForm("deptRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
async function handleAdd(row) {
  reset();
  deptCodeDisabled.value = false;
  await listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, "deptId");
  });
  if (row.deptId != undefined) {
    form.value.parentId = row.deptId;
  } else {
    if (deptId.value != undefined) {
      form.value.parentId = deptId.value[0];
    }
  }
  if(isVoid(form.value.parentId)){
    // proxy.$refs.parentIdRef.('');
  }
  open.value = true;
  title.value = "添加部门";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

function handleBeforeUpdate() {
  handleUpdate(selectRowData.value[0]);
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  deptCodeDisabled.value = true;
  await listDeptExcludeChild(row.deptId).then(response => {
    deptOptions.value = proxy.handleTree(response.data, "deptId");
    getDept(row.deptId).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改部门";
    });
  });

}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate(valid => {
    if (valid) {
      if (form.value.deptId != undefined) {
        updateDept(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDept(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleBeforeDelete() {
  handleDelete(selectRowData.value[0]);
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项?').then(function () {
    return delDept(row.deptId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}


/** 选中数据 */
function handleSelectionChange(selection) {
  rowSelect.value = selection.length != 1;
  deptId.value = selection.map(item => item.deptId);
  var deptNamearr = selection.map(item => item.deptName);
  allocateQueryParams.value.deptName = deptNamearr[0];
  allocateQueryParams.value.deptId = deptId.value[0];
  selectRowData.value = selection;
  if (selection.length > 0 && selection[0].parentId != 0) {
    delDisable.value = false;
  } else {
    delDisable.value = true;
  }
}


//点击分配用户按钮
async function handleAllocateUser() {
  getAllocateUser();
  allocateOpen.value = true;
  allocateTitle.value = allocateQueryParams.value.deptName + "分配用户";
  // await listDeptExcludeChild(deptId.value[0]).then(response => {
  //    deptOptions.value = proxy.handleTree(response.data, "deptId");
  // });
}

onMounted(() => {
  setTimeout(() => {
    loading.value = false;
  }, 300);
  window.onresize = function temp() {
    screenHeight.value = document.documentElement.clientHeight - 350 + "px;";
    dialogHeight.value = document.documentElement.clientHeight - 300 + "px;";
  };
})

//点击分配用户里的搜索按钮
function handleAllocateQuery() {
  queryParams.value.pageNum = 1;
  getAllocateUser();
}


function allocateUserHandleSelectionChange(selection) {
  userIds.value = selection.map(item => item.userId);
  var deptIds = selection.map(item => item.deptId);
  if (userIds.value.includes(1) === true || deptIds.includes(parseInt(deptId.value[0])) === true) {
    adminShow.value = true
  } else {
    adminShow.value = false
  }

  allocateSingle.value = selection.length != 1;
  allocateMultiple.value = !selection.length;
}

function submitAllocate() {
  var data = [];
  var userDept = {};
  userIds.value.forEach((item, index, arr) => {
    var userDept = {
      "userId": item,
      "deptId": deptId.value[0]
    }
    data.push(userDept);

  })
  allocateUsers(data).then(response => {
    proxy.$modal.msgSuccess("分配成功");
    handleAllocateQuery();
    // allocateOpen.value = false;
  });
}


function submitDisAllocate() {
  var data = [];
  var userDept = {};
  userIds.value.forEach((item, index, arr) => {
    var userDept = {
      "userId": item,
      "deptId": allocateQueryParams.value.deptId
    }
    data.push(userDept);
  })
  disAllocateUsers(data).then(response => {
    proxy.$modal.msgSuccess("取消分配成功");
    handleAllocateQuery();
  });
}

function leaderFormatter(row) {
  if (isNotVoid(row.leader) && row.leader.length > 1) {
    return row.leader.substring(0);
  }
}


getList();
</script>
